package top.v5it.japi.ddd.core.web;

import cn.hutool.core.io.FileUtil;
import cn.hutool.extra.servlet.ServletUtil;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.v5it.japi.ddd.core.service.FileService;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * 文件上传接口
 *
 * @author zhanpu
 * @date 2023/4/13
 */
@Slf4j
@Setter
@RestController
@ConfigurationProperties("spring.japi.ddd.upload")
public class UploadController extends BaseController {

    private String fileTmpPath = "/tmp/";

    @RequestMapping(value = "upload/{bean}", method = {RequestMethod.GET, RequestMethod.POST})
    public Object upload(@PathVariable("bean") String beanName, @RequestParam("file") MultipartFile file, HttpServletRequest request) {
        HttpHeadFactory.INSTANCE.putRequestHeadAll(ServletUtil.getHeaderMap(request));
        // 获取上传文件的原始文件名
        final String fileName = file.getOriginalFilename();
        // 获取上传文件的大小
        final long fileSize = file.getSize();
        log.debug("上传文件名：{}，大小：{}", fileName, fileSize);
        FileService service = (FileService) getBean(beanName);
        // 处理上传文件，并返回上传结果
        try (final InputStream in = file.getInputStream()) {
            final File dest = FileUtil.writeFromStream(in, fileTmpPath + fileName);
            return service.processor(dest, toMap(null, request));
        } catch (IOException e) {
            throw new RuntimeException("[" + fileName + "]上传失败");
        }
    }
}